﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Volo.Abp;
using Volo.Abp.Modularity;

namespace Kstopa.Cache
{

    public class KstopaAbpCacheModule : AbpModule
    {
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var services = context.Services;
            var configuration = context.Services.GetConfiguration();

            Configure<CacheSettingsOptions>(configuration.GetSection(nameof(CacheSettingsOptions)));
            //禁止在主机启动时通过 services.GetRequiredService<IOptions<CacheSettingsOptions>>().Value 获取选项，如需获取配置选项理应通过 。
            var cacheSettings = new CacheSettingsOptions();
            configuration.Bind("CacheSettingsOptions", cacheSettings);

            if (cacheSettings.UseRedis)
            {
                var connectionString =
                    $"server={cacheSettings.RedisSettings.Address};password={cacheSettings.RedisSettings.Password};db={cacheSettings.RedisSettings.Db}";
                //注入redis
                services.AddSimpleRedis(connectionString);
                services.AddSingleton<ISimpleCacheService, RedisCacheService>();
            }
            else
            {
                services.AddSingleton<ISimpleCacheService, MemoryCacheService>();
            }


        }

        public override Task OnPreApplicationInitializationAsync(ApplicationInitializationContext context)
        {
            var services = context.ServiceProvider;
            var cacheSettings = services.GetRequiredService<IOptions<CacheSettingsOptions>>().Value;
            if (cacheSettings.UseRedis && cacheSettings.RedisSettings.ClearRedis)
            {
                var redis = services.GetRequiredService<ISimpleCacheService>();//获取redis服务
                                                                               //删除redis的key
                redis.DelByPattern(CacheConst.Cache_Prefix_Web);
            }

            return Task.CompletedTask;
        }


    }
}
